package com.huyanqi.core.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class MD5Tools {

    public static String toMd5(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    /**
     * ����
     * @param args
     * @throws Exception
     */
/*    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage:java DigitalSignature2Example ");
            System.exit(1);
        }

        byte[] plainText = args[0].getBytes("UTF8");
        //�γ�RSA��Կ��
        //System.out.println("\nStart generating RSA key");
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair key = keyGen.generateKeyPair();
        //System.out.println("Finish generating RSA key");
        //ʹ��˽?ǩ��
        Signature sig = Signature.getInstance("SHA1WithRSA");
        sig.initSign(key.getPrivate());
        sig.update(plainText);
        byte[] signature = sig.sign();
       // System.out.println(sig.getProvider().getInfo());
       // System.out.println("\nSignature:");
       // System.out.println(new String(signature, "UTF8"));

        //ʹ�ù�?��֤
       // System.out.println("\nStart signature verification");
        sig.initVerify(key.getPublic());
        sig.update(plainText);
        try {
            if (sig.verify(signature)) {
              //  System.out.println("Signature verified");
            } //else System.out.println("Signature failed");
        } catch (SignatureException e) {
           // System.out.println("Signature failed");
        }
    }
*/    
    /**
    * 压缩图片方法
    * 
    * @param oldFile 将要压缩的图片
    * @param width 压缩宽
    * @param height 压缩高
    * @param quality 压缩清晰度 <b>建议为1.0</b>
    * @param smallIcon 压缩图片后,添加的扩展名（在图片后缀名前添加）
    * @param percentage 是否等比压缩 若true宽高比率将将自动调整
    * @author slzs
    * @return 如果处理正确返回压缩后的文件名 null则参数可能有误
    */
    public static String doCompress(String oldFile, int width, int height, float quality, String smallIcon, boolean percentage) {
       if (oldFile != null && width > 0 && height > 0) {
         Image srcFile=null;
        String newImage = null;
        try {
         File file = new File(oldFile);
         // 文件不存在
         if (!file.exists()) {
          return null;
         }
         /*读取图片信息*/
         srcFile = ImageIO.read(file);
         int new_w = width;
         int new_h = height;
         if (percentage) {
          // 为等比缩放计算输出的图片宽度及高度
          double rate1 = ((double) srcFile.getWidth(null)) / (double) width + 0.1;
          double rate2 = ((double) srcFile.getHeight(null)) / (double) height + 0.1;
          double rate = rate1 > rate2 ? rate1 : rate2;
          new_w = (int) (((double) srcFile.getWidth(null)) / rate);
          new_h = (int) (((double) srcFile.getHeight(null)) / rate);
         }
         /* 宽高设定*/
         BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
         tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);

         /*压缩后的文件名 */
         String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.'));
         newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());

         /*压缩之后临时存放位置*/
         FileOutputStream out = new FileOutputStream(newImage);

         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
         JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);

         /* 压缩质量 */
         jep.setQuality(quality, true);
         encoder.encode(tag, jep);

         out.close();

        } catch (FileNotFoundException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        }finally{
         srcFile.flush();
        }
        return newImage;
       } else {
        return null;
       }
    }

    //图片压缩测试
    public static void main(String str[]) {
       System.out.println(doCompress("D:\\Java\\workspace\\SHXDB\\WebRoot\\images\\imgchannel\\64_1.jpg", 200, 60, 1, "_small", false));
    }
    
}
